package com.ruoyi.system.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.SysStudentInteraction;
import com.ruoyi.system.service.SysStudentInteractionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学生课堂互动记录控制器
 *
 * @author ruoyi
 * @date 2025-08-29
 */
@RestController
@RequestMapping("/system/interaction")
public class SysStudentInteractionController extends BaseController
{
    @Autowired
    private SysStudentInteractionService interactionService;

    /**
     * 获取当前用户的互动记录
     */
    @GetMapping("/my")
    public AjaxResult getMyInteractions() {
        Long userId = getUserId(); // 从当前登录上下文获取用户ID
        List<SysStudentInteraction> list = interactionService.getInteractionsByUserId(userId);
        return AjaxResult.success(list);
    }

    /**
     * 按时间范围查询当前用户的互动记录
     */
    @GetMapping("/my/byTime")
    public AjaxResult getMyInteractionsByTime(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {
        Long userId = getUserId();
        List<SysStudentInteraction> list = interactionService
                .getInteractionsByUserIdAndTimeRange(userId, startTime, endTime);
        return AjaxResult.success(list);
    }

    /**
     * 按课程查询当前用户的互动记录
     */
    @GetMapping("/my/byCourse/{courseId}")
    public AjaxResult getMyInteractionsByCourse(@PathVariable Long courseId) {
        Long userId = getUserId();
        List<SysStudentInteraction> list = interactionService
                .getInteractionsByUserIdAndCourseId(userId, courseId);
        return AjaxResult.success(list);
    }

    /**
     * 获取当前用户的互动统计
     */
    @GetMapping("/my/statistics")
    public AjaxResult getMyInteractionStatistics() {
        Long userId = getUserId();
        Map<String, Object> result = new HashMap<>();
        result.put("totalCount", interactionService.countTotalInteractions(userId));
        result.put("typeDistribution", interactionService.countInteractionsByType(userId));
        return AjaxResult.success(result);
    }

    /**
     * 新增互动记录
     */
    @PostMapping
    public AjaxResult addInteraction(@RequestBody SysStudentInteraction interaction) {
        // 确保用户ID与当前登录用户一致，防止越权
        interaction.setUserId(getUserId());
        return toAjax(interactionService.addInteraction(interaction) ? 1 : 0);
    }
}
